package ca.eloas.judging.rest.security;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author JP
 */
@Singleton
public class PageSecurityFilter implements Filter {


    @Inject
    AuthenticationAuthorizationService security;

    public void destroy() {

    }

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String path = req.getRequestURL().toString();
        if ( path.contains("/admin") || path.contains("/profile")) {

            if ( ! security.isAuthenticated() ) {

                redirectIntelligently(req, resp);
                return;
            }
        }

        if ( path.contains("/admin")) {

            if (!  security.isAdmin()) {

                resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid Role");
                return;
            }
        }

        chain.doFilter(request, response);
    }

    private void redirectIntelligently(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String path = req.getRequestURL().toString();
        resp.sendRedirect("/site/login.html?returnTo=" + path);
    }
}
